package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    ISeckillVoucherService seckillVoucherService;

    @Resource
    RedisIdWorker redisIdWorker;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * @param voucherId
     * @return com.hmdp.dto.Result
     * @description 秒杀代金券
     * @author 31115
     * @date 2022/11/24 22:37
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //先判断时间
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            log.info("购买秒杀代金券活动还没开始！");
            return Result.fail("购买秒杀代金券活动还没开始！");
        }
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            log.info("购买秒杀代金券活动已经结束了！");
            return Result.fail("购买秒杀代金券活动已经结束了！");
        }
        //判断代金券数量
        if (voucher.getStock() <= 0) {
            log.info("秒杀代金券已经卖完！");
            return Result.fail("秒杀代金券已经卖完！");
        }

        UserDTO user = UserHolder.getUser();
        SimpleRedisLock lock = new SimpleRedisLock("order:" + user.getId(), stringRedisTemplate);
        boolean tryLock = lock.tryLock(1200L);
        if (!tryLock) {
            //没获取成功
            log.info("秒杀券订单获取锁不成功！");
            return Result.fail("不允许重复购买！");
        }
        //创建接口代理对象
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            log.info("秒杀卷订单支付成功支付人id：" + user.getId());
            return proxy.createVoucherOrder(voucherId);
        } catch (IllegalStateException e) {
            log.error("秒杀卷订单异常,异常结果：" + e);
            return Result.fail("秒杀卷订单异常,异常结果：" + e);
        } finally {
            //释放锁
            lock.unlock();
            log.info("秒杀卷订单 释放锁成功！");
        }
    }

    @Override
    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        UserDTO user = UserHolder.getUser();
        //查询订单
        int count = query().eq("user_id", user.getId()).eq("voucher_id", voucherId).count();

        if (count > 0) {
            log.info("您已购买过此优惠券！");
            return Result.fail("您已购买过此优惠券!");
        }

        //修改库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();

        if (!success) {
            log.info("秒杀代金券已经卖完！");
            return Result.fail("秒杀代金券已经卖完！");
        }
        //存入代金券 订单表 主键id 用户id 代金券id
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(redisIdWorker.nexId("voucherOrder" + voucherId));
        voucherOrder.setUserId(user.getId());
        voucherOrder.setVoucherId(voucherId);
        Long orderId = voucherOrder.getId();
        this.saveOrUpdate(voucherOrder);

        //返回订单id
        return Result.ok(orderId);
    }
}
